/**
 * @author : wangbo
 * @date : 2020-11-01 18:28
 **/
package com.ohaku.processor;

import com.ohaku.anno.DefaultValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.util.stream.Stream;

@Component
public class DefaultValueAllPostProcess implements BeanPostProcessor {

    private static final Logger logger = LoggerFactory.getLogger(DefaultValueAllPostProcess.class);


    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName)
            throws BeansException {
        System.out.println("postProcessAfterInitialization：" + bean + "," + beanName);
        return bean;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName)
            throws BeansException {
        System.out.println("postProcessBeforeInitialization： " + bean + "," + beanName);


        Stream.of(bean.getClass().getDeclaredFields())
                .filter(field -> field.getAnnotation(DefaultValue.class) != null)
                .forEach(field -> {
                    DefaultValue defaultValue = field.getAnnotation(DefaultValue.class);
                    try {
                        field.setAccessible(true);
                        field.set(bean, defaultValue.value());
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }

                    logger.info("dragon name = " + field.getName());
                    logger.info("dragon value = " + defaultValue.value());


                });


        return bean;
    }

}